package com.xuhai.blog19.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuhai.blog19.admin.dao.ExpiresDao;
import com.xuhai.blog19.admin.entity.ExpiresEntity;
import com.xuhai.blog19.admin.service.ExpiresService;
import com.xuhai.blog19.common.shiro.TokenGenerator;
import com.xuhai.blog19.common.utils.R;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author PangJunjie
 * @Date 2023/2/6/006
 */
@Service
public class ExpiresServiceImpl extends ServiceImpl<ExpiresDao, ExpiresEntity> implements ExpiresService {
    @Override
    public ExpiresEntity getByToken(String token) {
        return this.getOne(new QueryWrapper<ExpiresEntity>().eq("token", token));
    }

    @Override
    public R saveToken(int userId) {
        String token = TokenGenerator.generateValue();
        Date date = new Date();
        date.setHours(date.getHours() + 6);
        ExpiresEntity entity = getByUserId(userId);
        if (entity == null) {
            entity = new ExpiresEntity();
            entity.setUserId(userId);
            entity.setToken(token);
            entity.setExpires(date);
            this.save(entity);
        } else {
            entity.setToken(token);
            entity.setExpires(date);
            this.updateById(entity);
        }
        return R.ok().data(token);
    }

    @Override
    public void logout(int userId) {
        ExpiresEntity entity = getByUserId(userId);
        if (entity != null) {
            entity.setToken(TokenGenerator.generateValue());
            this.updateById(entity);
        }
    }

    @Override
    public ExpiresEntity getByUserId(int userId) {
        return this.getOne(new QueryWrapper<ExpiresEntity>().eq("user_id", userId));
    }
}
